package com.twetec.cms.service.website.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.dao.mapper.website.ArticleRelevantMapper;
import com.twetec.cms.model.po.website.ArticleRelevantPO;
import com.twetec.cms.model.vo.website.ArticleRelevantVO;
import com.twetec.cms.service.website.ArticleRelevantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 相关文章表 服务实现类
 * </p>
 *
 * @author zhxl
 * @since 2021-10-08
 */
@Service
public class ArticleRelevantServiceImpl extends ServiceImpl<ArticleRelevantMapper, ArticleRelevantPO> implements ArticleRelevantService {

    @Autowired
    private ArticleRelevantMapper articleRelevantMapper;
    @Override
    public boolean saveOrUpdateRelevent(Long articleId, String articleRelevantListJson, Long userId) {

        // 先查询相关文章表中是否有记录
        QueryWrapper<ArticleRelevantPO> articleRelevantPOQueryWrapper = new QueryWrapper<>();
        articleRelevantPOQueryWrapper.eq("ARTICLE_ID",articleId);
        List<ArticleRelevantPO> articleRelevantPOList = articleRelevantMapper.selectList(articleRelevantPOQueryWrapper);
        // 如果有记录就先删除
        if (!ValidateUtil.isNullOrEmpty(articleRelevantPOList)) {
            ArrayList<Long> relevantList = new ArrayList<>();
            for (ArticleRelevantPO articleRelevantPO : articleRelevantPOList) {
                relevantList.add(articleRelevantPO.getId());
            }
            articleRelevantMapper.deleteBatchIds(relevantList);
        }
        // 再添加
        if (StringUtils.isNotEmpty(articleRelevantListJson)) {

            List<ArticleRelevantVO> relevantList = JSONArray.parseArray(articleRelevantListJson, ArticleRelevantVO.class);
            for (ArticleRelevantVO relevantId : relevantList) {
                ArticleRelevantPO articleRelevantPO = new ArticleRelevantPO();
                articleRelevantPO.setArticleId(articleId);
                articleRelevantPO.setRelevantArticleId(relevantId.getRelevantArticleId());
                articleRelevantPO.setCreatorId(userId);
                articleRelevantPO.setModifierId(userId);
                articleRelevantMapper.insert(articleRelevantPO);
            }
        }
        return true;
    }
}
